import { Player, system, TicksPerSecond, world } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { cmd, isAdmin } from "../SAPI-Pro/func.js";
import { Configdb } from "../SAPI-Pro/main.js";
import { musicList } from "./musicList.js";
var lastTime = 0;
var playList = []; //播放列表
var playListback = []; //顺序播放列表备份
var currentPlay = undefined;
var doMusicplay = false;
var playMode = "顺序播放";
var lrcindex = 0; //当前歌词下标
var lrcindex0 = 0; //下一歌词下标
var lrcchange = false; //歌词改变标识
var Volume = 1.0;

musicList.sort((a, b) => {
  if (a.album == b.album) return a.name > b.name ? 1 : -1;
  return a.album > b.album ? 1 : -1;
});

world.afterEvents.worldLoad.subscribe(() => {
  const volume = Configdb.get("volume");
  if (volume) {
    Volume = volume;
  }
});

//获取歌手和专辑
const ArtistList = {};
const AlbumList = {};
for (let i = 0; i < musicList.length; i++) {
  let music = musicList[i];
  if (ArtistList.hasOwnProperty(music.singer)) {
    ArtistList[music.singer]["list"].push(i);
    ArtistList[music.singer]["cnt"]++;
  } else {
    ArtistList[music.singer] = { cnt: 1, list: [i] };
  }
  if (AlbumList.hasOwnProperty(music.album)) {
    AlbumList[music.album]["list"].push(i);
    AlbumList[music.album]["cnt"]++;
  } else {
    AlbumList[music.album] = { cnt: 1, list: [i] };
  }
}
const JoinedValidator = (player) => {
  return player.hasTag("nomusic") ? "未加入一起听歌" : true;
};
export const musicCommandObject = {
  name: "music",
  explain: "打开音乐播放器UI",
  handler: (player, args) => {
    musicForm(player, 10);
  },
  subCommands: [
    {
      name: "join",
      explain: "加入一起听歌",
      handler: (player, args) => {
        system.run(() => {
          joinMusic(player, true);
        });
      },
      validator: (player) => {
        if (JoinedValidator(player) == true) {
          return "请不要重复加入";
        } else {
          return true;
        }
      },
    },
    {
      name: "exit",
      explain: "退出一起听歌",
      validator: JoinedValidator,
      handler: (player, args) => {
        system.run(() => {
          joinMusic(player, false);
        });
      },
    },
    {
      name: "stop",
      explain: "停止播放",
      handler: (player, args) => {
        system.run(() => stopMusic(player));
      },
      validator: JoinedValidator,
    },
    {
      name: "list",
      explain: "列出音乐",
      handler: (player, args) => {
        listMusic(player, [args["页码/关键词"], args.页码1]);
      },
      paramBranches: [
        [
          { name: "页码/关键词", type: "string", optional: true },
          {
            name: "页码1",
            type: "int",
            optional: true,
          },
        ],
      ],
      validator: JoinedValidator,
    },
    {
      name: "add",
      explain: "添加音乐",
      handler: (player, args) => {
        addMusic([args["序号/关键词/范围"]], player);
      },
      paramBranches: [{ name: "序号/关键词/范围", type: "string" }],
      validator: JoinedValidator,
    },
    {
      name: "seq",
      explain: "查看播放列表",
      handler: (player, args) => {
        musicSeq(player, [args.页数 - 1]);
      },
      paramBranches: [
        { name: "页数", type: "int", optional: true, default: 1 },
      ],
      validator: JoinedValidator,
    },
    {
      name: "play",
      explain: "播放音乐",
      handler: (player, args) => {
        system.run(() => {
          playMusic(player, [args.序号 || args.顺序 || "s"]);
        });
      },
      paramBranches: [
        {
          name: "顺序",
          type: "enum",
          enums: ["r", "s", "c"],
          optional: true,
        },
        {
          name: "序号",
          type: "int",
          optional: true,
        },
      ],
      validator: JoinedValidator,
    },
    {
      name: "reset",
      explain: "重置播放列表",
      handler: (player, args) => {
        resetList(player);
      },
      validator: JoinedValidator,
    },
    {
      name: "remove",
      explain: "移除音乐",
      handler: (player, args) => {
        removeMusic(args["序号|序号对|范围"], player);
      },
      validator: JoinedValidator,
      paramBranches: [
        {
          name: "序号|序号对|范围",
          type: "string",
        },
      ],
    },
    {
      name: "next",
      explain: "播放下一首",
      handler: (player, args) => {
        system.run(() => {
          changeMusic(true, player);
        });
      },
      validator: JoinedValidator,
    },
    {
      name: "last",
      explain: "播放上一首",
      handler: (player, args) => {
        system.run(() => {
          changeMusic(false, player);
        });
      },
      validator: JoinedValidator,
    },
  ],
};
function mesAll(mes) {
  for (let player of getMusicPlayers()) {
    player.sendMessage("§7[一起听歌]§d" + mes);
  }
}
function mesPlayer(player, mes) {
  player.sendMessage("§7[一起听歌]§d" + mes);
}
function getMusicPlayers() {
  return world
    .getPlayers({ excludeTags: ["nomusic"] })
    .filter((p) => p != undefined);
}
/**
 * 播放上/下一首音乐
 * @param mode {bool} true为下一首，false为上一首
 * @param player {*} 玩家
 * @returns
 */
function changeMusic(mode, player) {
  if (playList.length == 0) return;
  let add = -1;
  let text = "上";
  let next = 0;
  if (mode) {
    add = 1;
    text = "下";
  }
  // if (playMode == "随机播放") {
  //     // next = Math.floor(Math.random() * (playList.length))
  // } else {
  next = currentPlay + add;
  if (next >= playList.length) next = 0;
  if (next < 0) next = playList.length - 1;
  // }
  playseq(next);
  mesAll(player.name + "切换到了" + text + "一首歌");
}
export function stopMusic(player) {
  doMusicplay = false;
  lastTime = 0;
  if (player) mesAll(player.name + "停止了一起听歌");
  cmd("stopsound @a[tag=!nomusic]");
}
export function joinMusic(player, j) {
  if (j) {
    player.removeTag("nomusic");
    showText("§7[一起听歌]§d您已加入一起听歌", player);
  } else {
    player.addTag("nomusic");
    showText("§7[一起听歌]§d您已退出一起听歌", player);
    player.runCommandAsync("stopsound @s");
  }
}
function resetList(player) {
  if (isAdmin(player)) {
    playList = [];
    currentPlay = undefined;
    stopMusic(player);
    mesAll(player.name + "清除了歌单中全部歌曲");
  }
}
function playMusic(player, text) {
  if (playList.length == 0) {
    showText("§7一起听歌]§d播放序列没有歌哦，请先去添加", player);
    return;
  }
  let id = currentPlay;
  let playMode = "顺序播放";
  switch (text[0]) {
    case "r":
      playMode = "随机播放";
      currentPlay = 0;
      break;
    case "c":
      playMode = "单曲循环";
      break;
    case "s":
      playMode = "顺序播放";
      break;
    default:
      //指定序号
      id = text[0] - 1;
  }
  if (id < 0 || id >= playList.length)
    return mesPlayer(player, "歌曲序号超出范围");
  mesAll(player.name + "开始了" + playMode);
  playseq(id);
}
function listMusic(player, args) {
  let len = 15;
  if (args[0] != undefined && args[0]?.replace(/[^\d]/g, "") == "") {
    findMusic(args, player);
  } else {
    let p = (args[0]?.replace(/[^\d]/g, "") ?? 1) - 1;
    showList(musicList, 15, p, player);
  }
}
function addMusic(text, player) {
  let id = 1;
  let count = 0;
  if (text[0] == undefined) return;
  //判断是否为单数字
  let condition = hasPara(text[0]);
  switch (condition) {
    case "数字":
      id = text[0]?.replace(/[^\d]/g, "") ?? "";
      if (id == "" || id > musicList.length || id < 1) {
        showText("§7[一起听歌]§d请正确输入歌曲序号", player);
        return;
      }
      id = id - 1;
      if (playList.indexOf(id) == -1) {
        playList.push(id);
        playListback.push(id);
        mesAll(
          player.name +
            "向歌曲列表添加了" +
            musicList[id].singer +
            "的" +
            musicList[id].name
        );
      } else {
        showText("§7[一起听歌]§d请勿重复添加", player);
      }
      break;
    case "逗号":
      //由，分隔的情况
      let idList = text[0].split(",");
      idList.forEach((t) => {
        let tt = t.replace(/[^\d]/g, "") - 1;
        if (
          String(tt) != "" &&
          tt * 1 > -1 &&
          tt * 1 < musicList.length &&
          playList.indexOf(tt) == -1
        ) {
          playList.push(tt);
          playListback.push(tt);
          count++;
        }
      });
      break;
    case "区间":
      id = text[0].split("-")[0].replace(/[^\d]/g, "");
      let id1 = text[0].split("-")[1].replace(/[^\d]/g, "");
      if (
        id1 == "" ||
        id1 > musicList.length ||
        id * 1 < 1 ||
        id * 1 > id1 * 1
      ) {
        showText("§7[一起听歌]§d请正确输入歌曲序号.", player);
        return;
      }
      id--;
      id1--;
      for (id; id * 1 <= id1 * 1; id++) {
        if (playList.indexOf(id) == -1) {
          playList.push(id);
          playListback.push(id);
          count++;
        }
      }
      break;
    case "查找":
      let List = findMusic(text, player, true);
      List.forEach((t) => {
        if (playList.indexOf(t.seq) == -1) {
          playList.push(t.seq);
          playListback.push(t.seq);
          count++;
        }
      });
      break;
  }
  if (condition != undefined && condition != "数字") {
    mesAll(player.name + "向歌曲列表添加了" + count + "首歌");
  }
}
//从歌单删除
function removeMusic(text, player) {
  if (text == undefined) return;
  let List = [];
  let id;
  let count = 0;
  let condition = hasPara(text);
  const lastmusic = playList[currentPlay];
  switch (condition) {
    case "数字":
      id = text.replace(/[^\d]/g, "") ?? "";
      if (id == "" || id > playList.length || id < 1) {
        mesPlayer(player, "请正确输入歌曲序号");
        return;
      }
      let music = musicList[playList[id - 1]];
      mesAll(player.name + "从歌单中删除了" + music.singer + "的" + music.name);
      playList.splice(id - 1, 1);
      playListback.splice(playListback.indexOf(playList[id - 1]), 1);
      //确保删除后能继续播放
      if (currentPlay == id - 1) playseq(currentPlay);
      currentPlay = currentPlay > id - 1 ? currentPlay - 1 : currentPlay;
      break;
    case "逗号":
      let idList = text.split(",");
      for (let i = 0; i < playList.length; i++) {
        if (idList.indexOf(i) == -1) {
          List.push(playList[i]);
        } else {
          count++;
        }
      }
      playList = List;
      break;
    case "区间":
      id = text.split("-")[0].replace(/[^\d]/g, "");
      let id1 = text.split("-")[1].replace(/[^\d]/g, "");
      if (
        id1 == "" ||
        id1 * 1 > playList.length ||
        id * 1 < 1 ||
        id * 1 > id1 * 1
      ) {
        mesPlayer(player, "请正确输入歌曲序号.");
        return;
      }
      id--;
      id1--;
      for (let i = 0; i < playList.length; i++) {
        if (i < id * 1 || i > id1 * 1) {
          List.push(playList[i]);
        } else {
          count++;
        }
      }
      playList = List;
  }
  if (condition != undefined && condition != "数字") {
    //保证删除后继续播放
    if (lastmusic != undefined) {
      const newid = playList.indexOf(lastmusic);
      if (newid != -1) {
        currentPlay = newid;
      } else {
        currentPlay = undefined;
      }
    }
    mesAll(player.name + "从歌单中删除了" + count + "首歌");
  }
}
function hasPara(text) {
  if (
    text?.split("-")[1]?.replace(/[^\d]/g, "") == undefined &&
    text?.split(",")[1]?.replace(/[^\d]/g, "") == undefined &&
    text.replace(/[^\d]/g, "") != ""
  ) {
    return "数字";
  } else if (
    text?.split(",")[1]?.replace(/[^\d]/g, "") != undefined &&
    text?.split("-")[1]?.replace(/[^\d]/g, "") == undefined
  ) {
    return "逗号";
  } else if (
    text?.split("-")[1]?.replace(/[^\d]/g, "") != undefined &&
    text?.split(",")[1]?.replace(/[^\d]/g, "") == undefined
  ) {
    return "区间";
  } else if (text.replace(/[^\d]/g, "") == "" && text != "") {
    return "查找";
  }
}
//查看歌单
function musicSeq(player, text) {
  if (playList.length == 0) {
    showText("§7[一起听歌]§d播放序列里没有歌哦", player);
    return;
  }
  let p = text[0] ?? 1 - 1;
  let i = 0;
  let len = 10;
  if (p >= 0 && p * len < playList.length) {
    i = p * len;
  } else {
    showText("§7[一起听歌]§d请正确输入页数", player);
    return;
  }
  showText("__________________\n§7[一起听歌]§d播放列表:", player);
  let ii = i + len;
  ii = Math.min(playList.length, ii);
  for (i; i < ii; i++) {
    let id = (i + 1).toString();
    if (i == currentPlay) id = "§l§o§s" + id;
    showText(
      id +
        "." +
        musicList[playList[i]].singer +
        "-" +
        musicList[playList[i]].name,
      player
    );
  }
  showText(
    "第" + (p + 1) + "页/共" + Math.ceil(playList.length / len) + "页",
    player
  );
}
//展示歌曲列表
function showList(List, len, p, player, mode) {
  let i = 0;
  if (mode == "find" && List.length == 0) {
    showText("§7[一起听歌]§d未查找到歌曲", player);
    return;
  }
  if (p * len < List.length && p >= 0) {
    i = p * len;
  } else {
    showText("§7[一起听歌]§d请正确输入页数", player);
    return;
  }
  showText("__________________\n§7[一起听歌]§d歌曲列表:", player);
  let ii = i + len;
  if (ii > List.length) ii = List.length;
  if (mode == "find") {
    for (i; i < ii; i++) {
      let id = List[i].seq + 1;
      showText(id + "." + List[i].singer + "-" + List[i].name, player);
    }
  } else {
    for (i; i < ii; i++) {
      let id = (i + 1).toString();
      showText(id + "." + List[i].singer + "-" + List[i].name, player);
    }
  }
  showText(
    "第" + (p * 1 + 1) + "页/共" + Math.ceil(List.length / len) + "页",
    player
  );
}
//查找歌曲
function findMusic(text, player, add) {
  let text1 = text[0].toLowerCase();
  let p = text[1] - 1;
  let List = [];
  for (let i = 0; i < musicList.length; i++) {
    let music = musicList[i];
    if (
      music.name.toLowerCase().indexOf(text1) != -1 ||
      music.singer.toLowerCase().indexOf(text1) != -1
    ) {
      let find = {
        seq: i,
        singer: music.singer,
        name: music.name,
      };
      List.push(find);
    }
  }
  if (add) return List;
  showList(List, 15, p, player, "find");
}
//循环主函数
export function musicPlay() {
  if (playList.length == 0) {
    currentPlay = undefined;
  }
  if (doMusicplay) {
    if (playList.length == 0) {
      cmd("stopsound @a[tag=!nomusic]");
      doMusicplay = false;
      return;
    }
    let music;
    if (currentPlay == undefined || playList[currentPlay] == undefined) {
      currentPlay = undefined; //勿删，可确保删除歌曲后正常播放
      music = { time: 0 };
    } else {
      music = musicList[playList[currentPlay]];
    }
    //判断是否播完
    if ((Date.now() - lastTime) / 1000 > music.time) {
      let next = 0;
      if (playMode == "单曲循环") {
        next = currentPlay;
      } else {
        next = currentPlay + 1;
        if (next >= playList.length) {
          next = 0;
        }
      }
      if (currentPlay == undefined) {
        next = 0;
      }
      playseq(next);
    }
  }
}
function shuffle(list) {
  let ans = [];
  for (let i = 0; i < list.length; i++) {
    let idx = Math.floor(Math.random() * (i + 1));
    ans[i] = ans[idx];
    ans[idx] = list[i];
  }
  return ans;
}
//播放播放列表中指定序号的歌曲
function playseq(seq = 0) {
  if (seq < 0 || seq >= playList.length) return;
  const music1 = musicList[playList[seq]];
  getMusicPlayers().forEach((p) =>
    p.onScreenDisplay.setActionBar(
      "§d开始播放:" + music1.singer + "-" + music1.name
    )
  );
  getMusicPlayers().forEach((p) => p.playMusic(music1.id, { volume: Volume }));
  currentPlay = seq;
  doMusicplay = true;
  lastTime = Date.now();
  lrcindex = 0;
  lrcindex0 = 0;
}

//歌词显示
export function showlrc() {
  if (
    doMusicplay &&
    currentPlay != undefined &&
    playList[currentPlay] != undefined
  ) {
    let music = musicList[playList[currentPlay]];
    if (lrcindex0 < music.lyrics.length && lrcchange) {
      // const player = world.getPlayers()[0];
      // player.sendMessage(`index0:${lrcindex0},index:${lrcindex}`);//调试用的
      world
        .getPlayers({ excludeTags: ["music_nolrc", "nomusic"] })
        .filter((p) => p != undefined)
        .forEach((p) =>
          p.onScreenDisplay.setTitle("musicplayerlrc", {
            fadeInDuration: 0,
            stayDuration: TicksPerSecond * 8,
            fadeOutDuration: 20,
            subtitle: music.lyrics[lrcindex0].text,
          })
        );
      lrcchange = false;
    }
    if (lrcindex >= music.lyrics.length) return;
    if (lrcindex == music.lyrics.length - 1) {
      lrcindex0 = lrcindex;
      lrcindex = music.lyrics.length;
      lrcchange = true;
      return;
    }
    let currentTime = (Date.now() - lastTime) / 1000;
    if (currentTime < music.lyrics[lrcindex].time) return;
    for (let i = lrcindex; i < music.lyrics.length; i++) {
      if (
        currentTime >= music.lyrics[i]?.time &&
        currentTime < music.lyrics[i + 1]?.time
      ) {
        lrcindex0 = i;
        lrcchange = true;
        lrcindex = i + 1;
        break;
      }
    }
  }
}
//使用rawtext显示文字
function showText(text, player) {
  if (player instanceof Player) {
    player.sendMessage(text);
  } else {
    cmd("tellraw " + player + ' {"rawtext":[{"text":"' + text + '"}]}');
  }
}
function lrctext(lrc) {
  let result = "";
  for (const line of lrc) {
    result = result + line.text + "\n";
  }
  if (result == "") {
    return "暂无歌词";
  }
  return result;
}
//主界面
export function musicForm(player, delay = 0) {
  if (player.hasTag("nomusic")) {
    const form = new ActionFormData()
      .title("MusicPlayer(join)")
      .button("加入一起听歌");
    system.runTimeout(() => {
      form.show(player).then((res) => {
        if (res.selection != undefined) {
          joinMusic(player, true);
        }
      });
    }, delay);
  } else {
    showUIForm(player, -1, musicListRender, musicListOpe, delay, 10, false);
  }
}
/**
 * 音乐播放器UI主控函数
 * @param {*} 玩家
 * @param page {Number} 页数
 * @param buttonRender {Function} 添加歌曲按钮的函数
 * @param buttonope {Function} 处理歌曲按钮点击操作函数
 * @param delay {Number} 延迟显示
 * @param limit {Number} 每页限制
 * @param openinfo {bool} 是否打开歌曲信息
 */
function showUIForm(
  player,
  page,
  buttonRender,
  buttonOpe,
  delay,
  limit = 10,
  openinfo = false
) {
  //通过标题来显示自定义UI
  const form = new ActionFormData().title("MusicPlayer");
  //先添加底栏
  let header = "0";
  if (openinfo) header = "3";
  if (currentPlay != undefined) {
    let music = musicList[playList[currentPlay]];
    form.button(header + "§r" + music.name, `textures/album/${music.icon}.png`);
    form.body(lrctext(music.lyrics));
  } else {
    form.button(header + "§r暂未播放歌曲", "textures/ui/blankcover");
    form.body("暂无歌词");
  }
  const buttonid = buttonRender(undefined, 0, 0);
  //左侧栏
  const precolor = ["1", "1", "1", "1"];
  const sectioncolor = ["§2", "§c", "§e", "§b"];
  precolor[buttonid] += sectioncolor[buttonid];
  form.button(precolor[0] + "歌曲", "textures/ui/music");
  form.button(precolor[1] + "专辑", "textures/ui/album");
  form.button(precolor[2] + "艺术家", "textures/ui/artist");
  form.button(precolor[3] + "播放队列", "textures/ui/playlist");
  form.button("1设置", "textures/ui/setting");
  //控制按钮
  form.button("2Last", "textures/ui/back");
  if (doMusicplay && currentPlay != undefined) {
    form.button("2Pause", "textures/ui/pause");
  } else {
    form.button("2Play", "textures/ui/play");
  }
  form.button("2Next", "textures/ui/next"); //8
  //添加右侧歌曲列表
  const [pre, next, p] = buttonRender(form, page, limit);
  if (page == -1) page = p;
  //定义第一个右侧按钮的下标
  const startid = 9;
  const musicstart = startid + Number(pre);
  //等待后显示界面
  system.runTimeout(() => {
    form.show(player).then((res) => {
      if (res.canceled) return;
      switch (res.selection) {
        case 1:
          showUIForm(player, 0, musicListRender, musicListOpe, 0, limit, false);
          break;
        case 2:
          showUIForm(player, 0, albumRender, albumOpe, 0, limit, false);
          break;
        case 3:
          showUIForm(player, 0, artistRender, artistOpe, 0, limit, false);
          break;
        case 4:
          showUIForm(player, -1, playListRender, playListOpe, 0, limit, false);
          break;
        case 5:
          musicSettingForm(player, page, buttonRender, buttonOpe, limit);
          break;
        case 6:
          //上一首
          changeMusic(false, player);
          showUIForm(player, page, buttonRender, buttonOpe, 0, limit, true);
          break;
        case 7:
          if (doMusicplay) {
            stopMusic(player);
          } else {
            let mode = {
              随机播放: "r",
              顺序播放: "s",
              单曲循环: "c",
            };
            playMusic(player, mode[playMode]);
          }
          showUIForm(player, page, buttonRender, buttonOpe, 0, limit, true);
          break;
        case 8:
          //下一首
          changeMusic(true, player);
          showUIForm(player, page, buttonRender, buttonOpe, 0, limit, true);
          break;
        default:
          if (pre && res.selection == startid) {
            showUIForm(
              player,
              page - 1,
              buttonRender,
              buttonOpe,
              0,
              limit,
              false
            );
          } else if (next && res.selection == musicstart + limit) {
            showUIForm(
              player,
              page + 1,
              buttonRender,
              buttonOpe,
              0,
              limit,
              false
            );
          } else {
            const id = page * limit + res.selection - musicstart;
            let openform = buttonOpe(player, id);
            if (openform != true) {
              showUIForm(
                player,
                page,
                buttonRender,
                buttonOpe,
                0,
                limit,
                false
              );
            }
          }
      }
    });
  }, delay);
}
function musicListRender(form, page, limit) {
  if (form == undefined) return 0;
  if (page == -1) page = 0;
  const [pre, next] = pageRender(form, page, limit, musicList);
  return [pre, next, page];
}
function musicListOpe(player, id) {
  //歌不满直接拉满
  if (playList.length < musicList.length) {
    playList = Array.from(musicList);
    for (let i = 0; i < playList.length; i++) {
      playList[i] = i;
    }
    if (playMode == "随机播放") {
      playListback = playList;
      playList = shuffle(playList);
    }
  }
  addAndPlay(player, id);
}
function playListRender(form, page, limit) {
  if (form == undefined) return 3;
  //-1指的是跳转到当前播放歌曲所在页面
  if (page == -1) {
    page = 0;
    if (currentPlay != undefined) page = Math.floor(currentPlay / limit);
  }
  const func = (form, i) => {
    let music = musicList[playList[i]];
    if (i == currentPlay) {
      form.button("§6" + gentitle(music), `textures/album/${music.icon}`);
    } else {
      form.button(gentitle(music), `textures/album/${music.icon}`);
    }
  };
  const [pre, next] = pageRender(form, page, limit, playList, func);
  return [pre, next, page];
}
function playListOpe(player, id) {
  playseq(id);
  const music = musicList[playList[id]];
  mesAll(`${player.name}切换到了${music.singer}的${music.name}`);
}
function artistRender(form, page, limit) {
  if (form == undefined) return 2;
  if (page == -1) page = 0;
  const artistkeys = Object.keys(ArtistList);
  const func = (form, i) => {
    const artist = artistkeys[i];
    const cnt = ArtistList[artist].cnt.toString().split("").join("§§§");
    const music = musicList[ArtistList[artist].list[0]];
    form.button(
      `§☯${artist.split("").join("§☯")}§r§§§${cnt}§§§首`,
      `textures/album/${music.icon}`
    );
  };
  const [pre, next] = pageRender(form, page, limit, artistkeys, func);
  return [pre, next, page];
}
function artistOpe(player, id) {
  const artist = Object.keys(ArtistList)[id];
  const currentlist = ArtistList[artist].list;
  const render = (form, page, limit) => {
    if (form == undefined) return 2;
    const func = (form, i) => {
      let music = musicList[ArtistList[artist].list[i]];
      form.button(gentitle(music), `textures/album/${music.icon}`);
    };
    const [pre, next] = pageRender(form, page, limit, currentlist, func);
    return [pre, next, page];
  };
  const ope = (player, id) => {
    playList = ArtistList[artist].list;
    id = playList[id];
    if (playMode == "随机播放") {
      playListback = playList;
      playList = shuffle(playList);
    }
    addAndPlay(player, id);
  };
  showUIForm(player, 0, render, ope, 0, 10, false);
  return true;
}
function albumRender(form, page, limit) {
  if (form == undefined) return 1;
  if (page == -1) page = 0;
  const albumkeys = Object.keys(AlbumList);
  const func = (form, i) => {
    const name = albumkeys[i];
    const cnt = AlbumList[name].cnt.toString().split("").join("§§§");
    const music = musicList[AlbumList[name].list[0]];
    form.button(
      `§☯${name.split("").join("§☯")}§r§§§${cnt}§§§首`,
      `textures/album/${music.icon}`
    );
  };
  const [pre, next] = pageRender(form, page, limit, albumkeys, func);
  return [pre, next, page];
}
function albumOpe(player, id) {
  const name = Object.keys(AlbumList)[id];
  const currentlist = AlbumList[name].list;
  const render = (form, page, limit) => {
    if (form == undefined) return 1;
    const func = (form, i) => {
      let music = musicList[AlbumList[name].list[i]];
      form.button(gentitle(music), `textures/album/${music.icon}`);
    };
    const [pre, next] = pageRender(form, page, limit, currentlist, func);
    return [pre, next, page];
  };
  const ope = (player, id) => {
    playList = AlbumList[name].list;
    id = playList[id];
    if (playMode == "随机播放") {
      playListback = playList;
      playList = shuffle(playList);
    }
    addAndPlay(player, id);
  };
  showUIForm(player, 0, render, ope, 0, 10, false);
  return true;
}
/**
 * 向播放列表添加歌曲并立即播放
 * @param id {Number} 歌曲在musicList里的下标
 */
function addAndPlay(player, id) {
  let index = playList.indexOf(id);
  if (index == -1) {
    const current = currentPlay == undefined ? 0 : currentPlay + 1;
    playList.splice(current, 0, id);
    index = current;
  }
  playseq(index);
  const music = musicList[id];
  mesAll(`${player.name}切换到了${music.singer}的${music.name}`);
}
function gentitle(music) {
  const name = "§☯" + music.name.split("").join("§☯");
  const artist = "§§§" + music.singer.split("").join("§§§");
  const album = "§§§" + music.album.split("").join("§§§");
  return `${name}§r${artist}§§§-${album}`;
}
function pageRender(form, page, limit = 10, list, func = undefined) {
  let cnt = 0; //用来记录有多少个按钮
  let hasnext = false;
  let haspre = false;
  let maxpage = Math.ceil(list.length / limit);
  let start = limit * page;
  let end = Math.min(limit * (page + 1), list.length);
  // 判断有无上一页
  if (page > 0) {
    form.button("§☯上§☯一§☯页");
    haspre = true;
    cnt++;
  }
  // 遍历一页
  for (let i = start; i < end; i++) {
    // 若有自定义方法则执行
    if (func) {
      func(form, i);
    } else {
      let music = list[i];
      form.button(gentitle(music), `textures/album/${music.icon}`);
    }
    cnt++;
  }
  // 判断有无下一页
  if (page < maxpage - 1) {
    form.button("§☯下§☯一§☯页");
    hasnext = true;
    cnt++;
  }
  return [haspre, hasnext];
}
function musicSettingForm(player, page, buttonRender, buttonOpe, limit) {
  //转换播放模式为id
  let modeid = ["顺序播放", "随机播放", "单曲循环"];
  let modenum = modeid.indexOf(playMode);
  if (modenum == -1) modenum = 0;
  let nolrc = player.hasTag("music_nolrc");
  let form = new ModalFormData().title("音乐播放器");
  form.dropdown("选择播放模式", ["顺序播放", "随机播放", "单曲循环"], {
    defaultValueIndex: modenum,
  });
  form.slider("音量调节", 10, 100, {
    defaultValue: Volume * 100,
    valueStep: 1,
  });
  form.toggle("显示歌词", { defaultValue: !nolrc });
  form.show(player).then((res) => {
    if (res.formValues == undefined) {
      showUIForm(player, page, buttonRender, buttonOpe, 0, limit, false);
      return;
    }
    let ans = res.formValues;
    if (ans[0] != modenum) {
      if (playList.length == 0) {
        showUIForm(player, page, buttonRender, buttonOpe, 0, limit, false);
        return mesPlayer(player, "播放列表为空");
      }
      playMode = modeid[ans[0]];
      //处理随机与顺序播放列表转换
      if (playMode == "随机播放") {
        const musicid = playList[currentPlay];
        playListback = playList;
        playList = shuffle(playList);
        currentPlay = playList.indexOf(musicid);
      }
      if (playMode == "顺序播放" && modenum == 1) {
        const musicid = playList[currentPlay];
        const playListSet = new Set(playList);
        playList = playListback.filter((x) => playListSet.has(x));
        currentPlay = playList.indexOf(musicid);
      }
    }
    const volume = parseFloat((ans[1] / 100).toFixed(2));
    if (Volume != volume) {
      Volume = volume;
      Configdb.set("volume", Volume);
      mesAll(player.name + "已调整全局音量为:" + Volume.toFixed(2));
      cmd("music volume " + Volume);
    }
    if (ans[2]) {
      player.removeTag("music_nolrc");
    } else {
      player.addTag("music_nolrc");
    }
    showUIForm(player, page, buttonRender, buttonOpe, 0, limit, false);
  });
}
